import {useContext, useState} from "react";
import {Avatar, Button, Divider, List, message, Popover, Typography} from "antd";
import {useNavigate} from "react-router-dom";
import {hostContext} from "../../store/commonContext.jsx";
import UserModal from "../user/UserModal.jsx"
import cookie from "js-cookie";
import axios from "axios";

const {Text} = Typography;

const AvatarPopover = ({
                           user
                       }) => {
    const [visible, setVisible] = useState(false)
    const [modalVisible, setmodalVisible] = useState(false)
    const navigate = useNavigate()
    const host = useContext(hostContext)
    const token = cookie.get('access_token')
    const requestHeader = {headers: {'Authorization': 'Bearer ' + token}}

    const logout = async () => {
        const response = await axios.post(`${host}/oauth/logout`, requestHeader)
        if (response.status === 200) {
            cookie.remove('access_token')
            cookie.remove('user_id')
            message.success('退出成功~')
        }
        setTimeout(() => navigate("/"), 500)
    }

    const calculateAge = (birthDate) => {
        const today = new Date();
        const birth = new Date(birthDate);

        let age = today.getFullYear() - birth.getFullYear();
        const monthDiff = today.getMonth() - birth.getMonth();

        // 处理未到生日月份 或 同月但未到生日当天的情况
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
            age--;
        }

        return age;
    }


    const userData = [
        `年 龄: ` + calculateAge(user.birthday),
        `生 日: ` + user.birthday,
        `总收入: ` + `¥ ${Number(user.inChargeAmount).toLocaleString('en-US')}`,
        `总支出: ` + `¥ ${Number(user.outChargeAmount).toLocaleString('en-US')}`,
        `签 名: ` + user.signature
    ]
    const popoverContent = (
        <div style={{width: 240}}>
            <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                <Avatar
                    size={60}
                    src={user.avatar}
                    style={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s',
                        ':active': {transform: 'scale(0.95)'},

                    }}
                />
            </div>
            <div style={{textAlign: 'center'}}>
                <p style={{margin: '10px 0'}}>{user.nickName}</p>
                <p style={{margin: '-5px 0'}}>{user.email}</p>
            </div>
            <Divider style={{
                margin: '10px 0',
                borderColor: '#1890ff',
                borderTopWidth: 2
            }}/>
            <List
                size={"small"}
                dataSource={userData}
                renderItem={(item) =>
                    <List.Item>
                        <Text style={{margin: '-5px 0'}}>{item}</Text>
                    </List.Item>}
                split={false}
            />
            <Divider style={{
                margin: '10px 0',
                borderColor: '#1890ff',
                borderTopWidth: 2
            }}/>
            <div style={{display: 'flex', gap:10}}>
                <Button
                    type="primary"
                    block
                    onClick={() => {
                        setVisible(false)
                        setmodalVisible(true)
                    }}
                >
                    修改信息
                </Button>
                <Button
                    type="primary"
                    danger
                    block
                    onClick={logout}
                >
                    注销
                </Button>
            </div>
        </div>
    )

    return (
        <>
            <Popover
                content={popoverContent}
                trigger="click"
                visible={visible}
                onOpenChange={visible => setVisible(visible)}
                overlayClassName="avatar-popover"
                placement="bottomRight"
            >
                <Avatar
                    size={40}
                    src={user.avatar}
                    style={{
                        cursor: 'pointer',
                        transition: 'transform 0.2s',
                        ':active': {transform: 'scale(0.95)'}
                    }}
                />
            </Popover>

            <UserModal
                visible={modalVisible}
                onCancel={() => setmodalVisible(false)}
                user={user}
            />
        </>
    )
}


export default AvatarPopover